package com.dcivision.dms.extractor;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
import org.apache.poi.util.LittleEndian;

public class PowerPointTextExtractor extends AbstractTextExtractor {

  public static final String REVISION = "$Revision: 1.3.32.2 $";
  
  private static final Log log = LogFactory.getLog(PowerPointTextExtractor.class);

  public PowerPointTextExtractor(InputStream fis, String encoding) {
    POIFSReader r = new POIFSReader();

    try {
      MyPOIFSReaderListener lis = new MyPOIFSReaderListener();
      r.registerListener(lis);
      r.read(fis);
      while (!lis.isFinished()) {
        Thread.sleep(10);
      }
      log.debug("FINISHED");
      text = lis.getResult();
      log.debug(text);
    } catch (Exception e) {
      log.error(e, e);
    }
  }

  static class MyPOIFSReaderListener implements POIFSReaderListener {
    static int filename=1;
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    String result = null;
    boolean finished = false;

    public boolean isFinished() {
      return(this.finished);
    }

    public String getResult() {
      return(this.result);
    }

    public void processPOIFSReaderEvent(POIFSReaderEvent event) {
      PropertySet ps = null;
      try {
        org.apache.poi.poifs.filesystem.DocumentInputStream dis = null;

        synchronized (bao) {
          dis=event.getStream();
          byte btoWrite[]= new byte[dis.available()];
          dis.read(btoWrite,0,dis.available());
          for (int i=0;i <btoWrite.length-20;i++) {

            long type=LittleEndian.getUShort(btoWrite,i+2);
            long size=LittleEndian.getUInt(btoWrite,i+4);
            if (type==4008) {
               bao.write(btoWrite,i+4+1,(int)size+3);
            }
          }
          filename++;
        }
        result = new String(bao.toByteArray());
      } catch (Exception ex) {
        log.error("No property set stream: \" " + event.getPath() + event.getName() + "\" ");
        result = "";
        log.error(ex, ex);
        return;
      } finally {
        finished = true;
      }
    }
  }
}
